package com.alibaba.algo.apiimpl.feign;

import com.alibaba.algo.apiimpl.user.SysPositionServiceImpl;
import com.alibaba.algo.cooperation.common.BaseResult;
import com.alibaba.algo.cooperation.common.PagerEntity;
import com.alibaba.algo.cooperation.feign.service.PositionFeignService;
import com.alibaba.algo.cooperation.feign.vo.req.GetPositionDetailVo;
import com.alibaba.algo.cooperation.feign.vo.req.SelectPositionListByUserReqVO;
import com.alibaba.algo.cooperation.feign.vo.req.SelectPositionListRequestVO;
import com.alibaba.algo.cooperation.feign.vo.req.SelectPositionUserReqVO;
import com.alibaba.algo.cooperation.feign.vo.res.*;
import com.alibaba.algo.cooperation.usercenter.GlobalResultStatus;
import com.alibaba.algo.cooperation.usercomponent.vo.res.user.SelectRoleListResponseVO;
import com.alibaba.algo.core.base.YesOrNo;
import com.alibaba.algo.core.exception.BaseException;
import com.alibaba.algo.domain.user.SysPositionDomain;
import com.alibaba.algo.dtos.user.PositionUserDTO;
import com.alibaba.algo.dtos.user.SysPositionDTO;
import com.alibaba.algo.entity.user.SysPosition;
import com.alibaba.algo.exception.BaseErrorCode;
import com.alibaba.algo.util.StringUtil;
import com.alibaba.algo.utils.ConverterUtil;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author : WangZhiPan
 * @date : 2021/9/24 10:42
 */
@RestController
public class PositionFeignServiceImpl implements PositionFeignService {

    @Resource
    private SysPositionDomain positionDomain;

    @Resource
    private SysPositionServiceImpl sysPositionService;

    @Resource
    private SysPositionDomain sysPositionDomain;

    /**
     * 根据组织查询岗位信息
     *
     * @param orgId 组织标识
     * @return
     */
    @Override
    public BaseResult<List<SysPositionVO>> list(Long orgId) {
        List<SysPositionVO> vos = Lists.newArrayList();
        List<SysPositionDTO> positions = positionDomain.listPositionOrg(orgId);
        if (ObjectUtils.isEmpty(positions)) {
            return BaseResult.buildSuccess(vos);
        }
        vos = ConverterUtil.getInstance().mapAsList(positions, SysPositionVO.class);
        return BaseResult.buildSuccess(vos);
    }

    @Override
    public BaseResult<List<PositionUserInfoResVO>> qryUserListByPositionId(SelectPositionUserReqVO vo) {
        //岗位--用户
        //租户--角色--用户
        List<PositionUserDTO> positionUserDTOList = positionDomain.getUsers(vo);
        List<PositionUserInfoResVO> positionUserInfoResVOList = ConverterUtil.getInstance().mapAsList(positionUserDTOList, PositionUserInfoResVO.class);
        return BaseResult.buildSuccess(positionUserInfoResVOList);
    }

    @Override
    public BaseResult<FeignPositionDetailVo> getPositionDetail(GetPositionDetailVo vo) {
        if (vo.empty()) {
            return BaseResult.buildError(-1, "id和posCode至少传一个。");
        }
        if (StringUtil.isNotEmpty(vo.getPosCode()) && vo.getPosCode().length() > 100) {
            return BaseResult.buildError(-1, "posCode不允许超过100。");
        }
        SysPosition sysPosition = new SysPosition();
        BeanUtils.copyProperties(vo, sysPosition);
        SysPosition position = positionDomain.getPositionDetailWithIsDeleted(sysPosition);
        FeignPositionDetailVo resVO = ConverterUtil.getInstance().map(position, FeignPositionDetailVo.class);
        return BaseResult.buildSuccess(resVO);
    }

    /**
     * 根据用户信息获取岗位列表
     *
     * @param vo 用户信息
     * @return 角色列表
     */
    @Deprecated
    public BaseResult<List<PositionInfoResponseVO>> selectPositionListByUserV1(SelectPositionListByUserReqVO vo) {
        if (null == vo) {
            return BaseResult.buildError(BaseErrorCode.PARAM_IS_NULL.getCode(), BaseErrorCode.PARAM_IS_NULL.getMessage());
        }
        if (StringUtils.isEmpty(vo.getUserName())) {
            return BaseResult.buildError(BaseErrorCode.USER_NAME_IS_NULL.getCode(), BaseErrorCode.USER_NAME_IS_NULL.getMessage());
        }

        List<PositionUserDTO> positionUserDTOList = positionDomain.selectPositionListByUser(vo);
        List<PositionInfoResponseVO> positionInfoResponseVOList = new ArrayList<PositionInfoResponseVO>();
        if (CollectionUtils.isEmpty(positionUserDTOList)) {
            return BaseResult.buildSuccess(positionInfoResponseVOList);
        }

        Map<String, PositionInfoResponseVO> positionInfoResponseVOMap = new HashMap<>();
        for (PositionUserDTO positionUserDTO : positionUserDTOList) {
            PositionInfoResponseVO tmpPositionInfoResponseVO = null;
            if (positionInfoResponseVOMap.containsKey(positionUserDTO.getPosId() + "")) {
                tmpPositionInfoResponseVO = positionInfoResponseVOMap.get(positionUserDTO.getPosId() + "");
            } else {
                tmpPositionInfoResponseVO = new PositionInfoResponseVO();
                BeanUtils.copyProperties(positionUserDTO, tmpPositionInfoResponseVO);
                List<UserInfoResVO> userList = new ArrayList<>();
                tmpPositionInfoResponseVO.setUserList(userList);
                positionInfoResponseVOMap.put(positionUserDTO.getPosId() + "", tmpPositionInfoResponseVO);
            }

            UserInfoResVO userInfoResVO = new UserInfoResVO();
            BeanUtils.copyProperties(positionUserDTO, userInfoResVO);
            tmpPositionInfoResponseVO.getUserList().add(userInfoResVO);
        }

        positionInfoResponseVOList.addAll(positionInfoResponseVOMap.values());
        return BaseResult.buildSuccess(positionInfoResponseVOList);
    }

    /**
     * 根据用户信息获取岗位列表
     *
     * @param vo 用户信息
     * @return 角色列表
     */
    @Override
    public BaseResult<PagerEntity<PositionInfoResponseVO>> selectPositionListByUser(SelectPositionListByUserReqVO vo) {
        // 检查参数正确性
        if (null == vo) {
            return BaseResult.buildError(BaseErrorCode.PARAM_IS_NULL.getCode(), BaseErrorCode.PARAM_IS_NULL.getMessage());
        }
        if (null == vo.getPageIndex() || vo.getPageIndex() < 0) {
            return BaseResult.buildError(GlobalResultStatus.PARAM_PAGE_INDEX_ERROR.getCode(), GlobalResultStatus.PARAM_PAGE_INDEX_ERROR.getMsg());
        }
        if (null == vo.getPageSize() || vo.getPageSize() <= 0) {
            return BaseResult.buildError(GlobalResultStatus.PARAM_PAGE_SIZE_ERROR.getCode(), GlobalResultStatus.PARAM_PAGE_SIZE_ERROR.getMsg());
        }
        if (vo.getPageSize() > 10) {
            throw new BaseException(GlobalResultStatus.PARAM_PAGE_SIZE_OVERSIZE_ERROR.getCode(), GlobalResultStatus.PARAM_PAGE_SIZE_OVERSIZE_ERROR.getMsg());
        }

        // 分页查询符合条件的岗位列表
        LinkedHashMap<String, Object> sortMap = new LinkedHashMap<String, Object>();
        sortMap = ObjectUtils.isEmpty(vo.getSortMap()) ? sortMap : vo.getSortMap();
        sortMap.put("isPrimary", "DESC");
        sortMap.put("gmtCreated", "DESC");
        SysPosition positionCon = new SysPosition();
        BeanUtils.copyProperties(vo, positionCon);
        com.alibaba.algo.core.base.PagerEntity pagerEntity = sysPositionDomain.pageByPara(positionCon, vo.getPageIndex(), vo.getPageSize(), sortMap);
        List<SysPosition> sysPositionList = (List<SysPosition>) pagerEntity.getDataList();
        List<PositionInfoResponseVO> positionInfoResponseVOList = new ArrayList<>(sysPositionList.size());
        for (SysPosition tmpPosition : sysPositionList) {
            PositionInfoResponseVO tmpPositionInfoResponseVO = new PositionInfoResponseVO();
            BeanUtils.copyProperties(tmpPosition, tmpPositionInfoResponseVO);
            tmpPositionInfoResponseVO.setPosId(tmpPosition.getId());
            tmpPositionInfoResponseVO.setUserList(new ArrayList<>());
            positionInfoResponseVOList.add(tmpPositionInfoResponseVO);
        }
        PagerEntity<PositionInfoResponseVO> newPagerEntity = new PagerEntity(pagerEntity.getTotal(), pagerEntity.getTotalPages(), pagerEntity.getPageSize(), pagerEntity.getPageIndex(), positionInfoResponseVOList);
        if (CollectionUtils.isEmpty(pagerEntity.getDataList())) {
            return BaseResult.buildSuccess(newPagerEntity);
        }

        // 查询处理人员信息
        //获取组织ID清单
        List<Long> qryList = new ArrayList<>(newPagerEntity.getDataList().size());
        for (PositionInfoResponseVO item : newPagerEntity.getDataList()) {
            qryList.add(item.getPosId());
        }
        SelectPositionUserReqVO selectPositionUserReqVO = new SelectPositionUserReqVO();
        selectPositionUserReqVO.setPositionIdList(qryList);
        //批量查询用户清单
        List<PositionUserDTO> positionUserDTOList = positionDomain.selectUserListByPosition(selectPositionUserReqVO);
        Map<Long, PositionInfoResponseVO> tmpMap = new HashMap<>();
        for (PositionUserDTO positionUserDTO : positionUserDTOList) {
            PositionInfoResponseVO tmpPositionInfoResponseVO = null;
            if (tmpMap.containsKey(positionUserDTO.getPosId())) {
                tmpPositionInfoResponseVO = tmpMap.get(positionUserDTO.getPosId());
            } else {
                tmpPositionInfoResponseVO = new PositionInfoResponseVO();
                BeanUtils.copyProperties(positionUserDTO, tmpPositionInfoResponseVO);
                List<UserInfoResVO> userList = new ArrayList<>();
                tmpPositionInfoResponseVO.setUserList(userList);
                tmpMap.put(positionUserDTO.getPosId(), tmpPositionInfoResponseVO);
            }
            if (StringUtils.isNotEmpty(vo.getUserName())) {
                //用户名模糊|工号精确匹配
                if (positionUserDTO.getUserName().indexOf(vo.getUserName()) >= 0
                    || (StringUtils.isNotEmpty(positionUserDTO.getEmployeeCode()) && positionUserDTO.getEmployeeCode().equals(vo.getUserName()))
                ) {
                    UserInfoResVO tmpUserInfoResVO = new UserInfoResVO();
                    BeanUtils.copyProperties(positionUserDTO, tmpUserInfoResVO);
                    tmpPositionInfoResponseVO.getUserList().add(tmpUserInfoResVO);
                    tmpPositionInfoResponseVO.setUserQty(tmpPositionInfoResponseVO.getUserQty() + 1);
                }
            } else {
                tmpPositionInfoResponseVO.setUserQty(tmpPositionInfoResponseVO.getUserQty() + 1);
            }
        }
        for (PositionInfoResponseVO item : newPagerEntity.getDataList()) {
            PositionInfoResponseVO tmpPositionInfoResponseVO = tmpMap.get(item.getPosId());
            if (null == tmpPositionInfoResponseVO) {
                continue;
            }
            item.setUserList(tmpPositionInfoResponseVO.getUserList());
            item.setUserQty(tmpPositionInfoResponseVO.getUserQty());
        }
        return BaseResult.buildSuccess(newPagerEntity);
    }

    @Override
    public BaseResult<PagerEntity<SelectPositionListResponseVO>> selectPage(SelectPositionListRequestVO vo) {
        if (ObjectUtils.isEmpty(vo.getPageIndex())) {
            return BaseResult.buildError(GlobalResultStatus.PARAM_PAGE_INDEX_ERROR.getCode(), GlobalResultStatus.PARAM_PAGE_INDEX_ERROR.getMsg());
        }
        if (ObjectUtils.isEmpty(vo.getPageSize())) {
            return BaseResult.buildError(GlobalResultStatus.PARAM_PAGE_SIZE_ERROR.getCode(), GlobalResultStatus.PARAM_PAGE_SIZE_ERROR.getMsg());
        }
        if (vo.getPageSize() > 10) {
            throw new BaseException(GlobalResultStatus.PARAM_PAGE_SIZE_OVERSIZE_ERROR.getCode(), GlobalResultStatus.PARAM_PAGE_SIZE_OVERSIZE_ERROR.getMsg());
        }
        com.alibaba.algo.cooperation.usercomponent.vo.req.user.SelectPositionListRequestVO qryVO =
                new com.alibaba.algo.cooperation.usercomponent.vo.req.user.SelectPositionListRequestVO();
        BeanUtils.copyProperties(vo, qryVO);
        BaseResult<com.alibaba.algo.core.base.PagerEntity<com.alibaba.algo.cooperation.usercomponent.vo.res.user.SelectPositionListResponseVO>>
                orgResult = sysPositionService.selectPage(qryVO);
        BaseResult<PagerEntity<SelectPositionListResponseVO>> newResult = new BaseResult<>();
        BeanUtils.copyProperties(orgResult, newResult);
        return newResult;
    }

    /**
     * 获取岗位下的用户列表
     *
     * @param vo 岗位标识
     * @return 用户列表
     */
    @Override
    public BaseResult<List<PositionUserInfoResVO>> selectUserListByPosition(SelectPositionUserReqVO vo) {
        if (null == vo) {
            return BaseResult.buildError(BaseErrorCode.PARAM_IS_NULL.getCode(), BaseErrorCode.PARAM_IS_NULL.getMessage());
        }
        if (null == vo.getPositionId()
                && CollectionUtils.isEmpty(vo.getPositionIdList())
                && CollectionUtils.isEmpty(vo.getPositionCodes())) {
            return BaseResult.buildError(BaseErrorCode.PARAM_IS_NULL.getCode(), BaseErrorCode.PARAM_IS_NULL.getMessage());
        }
        vo.setIsDeleted(YesOrNo.N.name());
        List<PositionUserDTO> positionUserDTOList = positionDomain.selectUserListByPosition(vo);
        List<PositionUserInfoResVO> positionUserInfoResVOList = ConverterUtil.getInstance().mapAsList(positionUserDTOList, PositionUserInfoResVO.class);
        return BaseResult.buildSuccess(positionUserInfoResVOList);
    }

    @Override
    public BaseResult<List<PositionUserInfoResVO>> selectUserListWithIsDeletedByPosition(SelectPositionUserReqVO vo) {
        if (null == vo) {
            return BaseResult.buildError(BaseErrorCode.PARAM_IS_NULL.getCode(), BaseErrorCode.PARAM_IS_NULL.getMessage());
        }
        if (null == vo.getPositionId()
                && CollectionUtils.isEmpty(vo.getPositionIdList())
                && CollectionUtils.isEmpty(vo.getPositionCodes())) {
            return BaseResult.buildError(BaseErrorCode.PARAM_IS_NULL.getCode(), BaseErrorCode.PARAM_IS_NULL.getMessage());
        }
        List<PositionUserDTO> positionUserDTOList = positionDomain.selectUserListWithIsDeletedByPosition(vo);
        List<PositionUserInfoResVO> positionUserInfoResVOList = ConverterUtil.getInstance().mapAsList(positionUserDTOList, PositionUserInfoResVO.class);
        return BaseResult.buildSuccess(positionUserInfoResVOList);
    }
}
